package com.anjiplus.template.gaea.business.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUtil {
    @Autowired
    private static RestTemplate restTemplate ;

    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static File downloadFileFromUrl(String urlStr,String fileName,String savePath) {
        InputStream inputStream = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(5*1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            /* conn.setRequestProperty("lfwywxqyh_token",toekn);*/
            //得到输入流
            inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);

            //文件保存位置
            File saveDir = new File(savePath);
            //如果不存在目录，则创建
            if(!saveDir.exists()){
                saveDir.mkdir();
            }
            //路径+分隔符+文件名
            File file = new File(saveDir + File.separator + fileName);
            fos = new FileOutputStream(file);
            fos.write(getData);
            System.out.println("下载文件成功");
            return file;
        }catch (Exception e){
            return null;
        }finally {
            //必须关流
            if(fos != null){
                try {
                    fos.close();
                }catch (Exception e){
                    System.out.println("fos关流失败");
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                }catch (Exception e){
                    System.out.println("inputStream关流失败");
                }
            }
        }

    }



    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    public static String  createPost(String url,HttpHeaders headers,Map<String, Object> params){
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.add("token",token);

//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("checkResult", 0);
//        //默认查询最近3个月的
//        params.put("starttime", "null".equals(starttime) ? DateUtil.getFirstDateByLast3MonthString() : starttime);
//        //设置查询结束时间为当天的最后一秒，才能查询出当天的报警记录来
//        params.put("endtime", "null".equals(endtime) ? DateUtil.getCurrentDateString() + " 23:59:59" : endtime + " 23:59:59");
//        params.put("page", 1);
//        params.put("pagesize", 10000);
        HttpEntity<Map> requestEntity = new HttpEntity<>(params,headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
//        airTempAlarmList = JSONObject.parseArray(JSONObject.parseObject(response.getBody()).getString("Result"), AirTempAlarm.class);
        return response.getBody();
    }
}